package com.example.player.dao.viewmodel;

import android.util.Log;

import com.example.player.dao.SongDao;
import com.example.player.domain.entity.Song;
import com.example.player.presentation.adaptor.RecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * song的viewmodel层，用于数据与ui层解耦
 * @author 朱文权
 * */
public class SongViewModel {
    /**
     * dao层对象，用于数据库交互
     * */
    private SongDao dao;
    public SongViewModel(SongDao dao){
        this.dao=dao;
    }
    /**
     * 异步添加多条歌曲
     * */
    public Disposable insert(List<Song> songs){
        return dao.insertSongs(songs)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(()->Log.d("TAG","成功插入多条数据"),
                            error->Log.e("ERROR","插入多条数据失败"+error));
    }
    /**
     * 异步添加歌曲
     * */
    public Disposable insert(Song song){
        //异步添加歌曲
        return dao.insert(song)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        ()-> Log.d("TAG","成功插入音乐数据"),
                        error->Log.e("ERROR","插入音乐数据失败:"+error)
                );
    }
    /**
     * 异步删除歌曲
     * */
    public Disposable delete(Song song){
        //异步删除歌曲
        return dao.delete(song)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        ()-> Log.d("TAG","成功删除该条数据"),
                        error->Log.e("ERROR","删除音乐数据失败:"+error)
                );
    }
    /**
     * 异步获取本地所有歌曲并渲染在页面上
     * */
    public Flowable<List<Song>> getAllSongs(){
        return dao.getAllSongs()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
    /**
     * 异步获取收藏夹数据并渲染在页面上
     * */
    public Flowable<List<Song>> getPlayListSongs(Long pid){
        return dao.getPlayListSongs(pid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
    /**
     * 异步删除所有歌曲
     * */
    public Disposable deleteAll(){
        return dao.deleteAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        ()->Log.d("TAG","清除数据成功"),
                        error->Log.e("ERROR","清除数据失败："+ error.getMessage())
                );
    }
}
